package com.yonyou.distribute.service;

import com.yonyou.distribute.pojo.LocalStock;
import org.springframework.stereotype.Service;

import java.util.concurrent.locks.ReentrantLock;

@Service
public class LocalService {

    private LocalStock stock = new LocalStock();

    /**
     * 超卖
     */
    public void deduct1(){
        stock.setStock(stock.getStock() - 1);
        System.out.println("库存余量：" + stock.getStock());
    }

    /**
     * 解决单机超卖1
     */
    public synchronized void deduct2(){
        stock.setStock(stock.getStock() - 1);
        System.out.println("库存余量：" + stock.getStock());
    }

    /**
     * 解决单机超卖2
     */
    private ReentrantLock reentrantLock = new ReentrantLock();
    public synchronized void deduct(){
        reentrantLock.lock();
        try {
            stock.setStock(stock.getStock() - 1);
            System.out.println("库存余量：" + stock.getStock());
        }finally {
            reentrantLock.unlock();
        }
    }
}
